const {query}=require("../utils/query")

const {createId}=require("../utils/util")

// 获取数据总长度
const getCountService=async ()=>{
    // 获取长度
    const sql=`select count(*) from user_list`
    return await query(sql)
}

// 分页
const getPageService=async (pageSize,limit)=>{ //注意 数据类型  为number 不加双引号
    // 分页
    const sql=`select * from user_list limit ${pageSize},${limit}`
    return await query(sql)
}

// 搜索
const searchService=async (val)=>{
    // 搜索 
    const sql=`select * from user_list where nickname like "%${val}%"`
    return await query(sql)
}

// 编辑点击确定
const sureUserService=async ({id,username,nickname})=>{
    // 编辑
    const sql=`update user_list set username="${username}",nickname="${nickname}" where id="${id}"`
    return await query(sql)
}

//删除
const delUserService=async (id)=>{
    //删除语句
    const sql=`delete from user_list where id="${id}"`
    return await query(sql)
}

// 新增
const addUserService=async (obj)=>{
    // 新增数据需要id
    const id=createId(obj.username)
    //插入
    const sql=`insert into user_list (id,username,nickname,age,tel)values("${id}","${obj.username}","${obj.nickname}","${obj.age}","${obj.tel}")`
    return await query(sql)
}

const getUserService=async ()=>{
    //获取数据
    const sql=`select * from user_list`
    return await query(sql)
}


//登录
const loginService=async (username,pwd)=>{
    //sql 查询语句
    const sql=`select * from login where username="${username}" and pwd="${pwd}"`
    return await query(sql)
}

// 判断用户名是否已被注册
const registryCheckName=async username=>{
    //查询语句
    const sql=`select * from login where username="${username}"`
    const result= await query(sql)
    if(result.length){
        return false
    }else{
        return true
    }
}

//注册
const registryService=async (username,pwd)=>{
    const id=createId(username)
    // 插入语句
    const sql=`insert into login (id,username,pwd)values("${id}","${username}","${pwd}")`
    return await query(sql)
}

module.exports={
    loginService,
    registryService,
    registryCheckName,
    getUserService,
    addUserService,
    delUserService,
    sureUserService,
    searchService,
    getPageService,
    getCountService
}